
package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.exception.BadRequestException;
import com.weiqiao.mall.constant.e.InviterEnum;
import com.weiqiao.mall.domain.AccountDetailEntity;
import com.weiqiao.mall.domain.AppUserEntity;
import com.weiqiao.mall.domain.TeamEntity;
import com.weiqiao.mall.repository.IAccountDetaiRepository;
import com.weiqiao.mall.repository.IAppUserRepository;
import com.weiqiao.mall.repository.ITeamRepository;
import com.weiqiao.mall.service.IAppUserService;
import com.weiqiao.mall.service.dto.AppUserDTO;
import com.weiqiao.mall.service.dto.InviterDTO;
import com.weiqiao.mall.service.vo.InviterVO;
import com.weiqiao.mall.service.vo.RechargeBalanceVO;
import com.weiqiao.mall.util.ReturnMapUtil;
import com.weiqiao.modules.system.domain.User;
import com.weiqiao.modules.system.service.UserService;
import com.weiqiao.modules.system.service.dto.UserQueryCriteria;
import com.weiqiao.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("AppUserServiceImpl")
public class AppUserServiceImpl implements IAppUserService {

    /**
     * 客户管理数据层
     */
    @Autowired
    @Qualifier("AppUserRepositoryImpl")
    private IAppUserRepository appUserRepository;

    @Autowired
    private ITeamRepository teamRepository;

    /**
     * 流水数据层
     */
    @Autowired
    private IAccountDetaiRepository accountDetaiRepository;

    @Override
    public int countNum(int company_id, Bson filter) {
        return appUserRepository.countFruiter(company_id, filter);
    }

    @Override
    public List<AppUserDTO> getAppUserPage(int company_id, Bson filter, Pageable pageable) {
        List<String> list = appUserRepository.getUserPage(company_id, filter, pageable);
        List<AppUserDTO> appUserList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            for (String str : list) {
                AppUserDTO appUserEntity = new Gson().fromJson(str, AppUserDTO.class);
                this.workersEntityUpdate(appUserEntity, simpleDateFormat);
                appUserList.add(appUserEntity);
            }
        }
        return appUserList;
    }

    @Override
    public List<AppUserEntity> getCustomerUserPage(int company_id, Bson filter, Pageable pageable) {
        List<String> list = appUserRepository.getUserPage(company_id, filter, pageable);
        List<AppUserEntity> appUserList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            for (String str : list) {
                AppUserEntity appUserEntity = new Gson().fromJson(str, AppUserEntity.class);
                // 根据电话号，获取后台登录用户信息
                User user = userService.findUserByPhoneAndCompanyId(appUserEntity.getPhone(), appUserEntity.getCompany_id());
                if (!StringUtil.isBlank(user) && !StringUtil.isBlank(user.getUsername())) {
                    appUserEntity.setUser_name(user.getUsername());
                }
                appUserList.add(appUserEntity);
            }
        }
        return appUserList;
    }

    // 卡片加密
    private String hideBnakId(String str) {
        String regex = "(\\w{4})(.*)(\\w{4})";
        Matcher m = Pattern.compile(regex).matcher(str);
        if (m.find()) {
            String rep = m.group(2);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rep.length(); i++) {
                sb.append("*");
            }
            return str.replaceAll(rep, sb.toString());
        } else {
            return str;
        }
    }

    @Override
    public boolean updateMany(Document doc, Bson filter, int company_id) {
        return appUserRepository.updateMany(doc, filter, company_id);
    }

    @Override
    public List<Map<String, Object>> exportWorkersInfo(int company_id, String type, Bson filter) {
        List<Map<String, Object>> exportContent = new ArrayList<>();
        List<String> list = appUserRepository.getAppUserListByUserId(filter, company_id);
        if (list != null && list.size() > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            for (String str : list) {
                AppUserDTO entity = new Gson().fromJson(str, AppUserDTO.class);
                this.workersEntityUpdate(entity, simpleDateFormat);
                if ("0".equals(type)) { // 推广员列表导出
                    exportContent.add(createExcelContent(entity));
                }
                if ("1".equals(type)) { // 普通用户列表导出
                    exportContent.add(createExcelContent_ordinarylist(entity));
                }
            }
        }
        return exportContent;
    }

    // 实体内容进行补充，修改
    private void workersEntityUpdate(AppUserDTO entity, SimpleDateFormat simpleDateFormat) {
        if (StringUtils.isLong(entity.getCreate_time())) {
            entity.setCreate_time(simpleDateFormat.format(Long.parseLong(entity.getCreate_time())));
        }
        if (StringUtils.isLong(entity.getLast_buy_time())) {
            entity.setLast_buy_time(simpleDateFormat.format(Long.parseLong(entity.getLast_buy_time())));
        }
        if (!StringUtil.isBlank(entity.getPhone())) {
            entity.setPhone(entity.getPhone().replaceAll("(\\d{3})\\d{4}", "$1****"));
        }
        AppUserEntity.BankCardInfo cardInfo = entity.getBankCardInfo();
        if (cardInfo != null) {
            String card_id = cardInfo.getCard_id();
            if (!org.apache.commons.lang3.StringUtils.isBlank(card_id)) {
                card_id = this.hideBnakId(card_id);
            }
            entity.setBankInfo(cardInfo.getOwner_name() + ", " + card_id + ", " + cardInfo.getBank_type() + ", "
                    + cardInfo.getBank_name());
        }
        // 根据邀请人id查询出邀请人信息并回填
        AppUserEntity appuser =
                entity.getRecommend_id() == 0 ?
                        new AppUserEntity() :
                        getAppUserByFilter(Filters.eq("user_id", entity.getRecommend_id()), entity.getCompany_id());
        entity.setRecommend_name(appuser.getUser_name());
        entity.setRecommend_member_type(appuser.getMember_type());
    }

    /**
     * excel 内容组装
     *
     * @param user 退官员列表信息
     */
    public Map<String, Object> createExcelContent(AppUserEntity user) {
        Map map = new LinkedHashMap();
        map.put("用户编号", user.getUser_id());
        map.put("手机号码", user.getPhone());
        map.put("微信昵称", user.getNickname());
        map.put("用户姓名", user.getUser_name());
        map.put("账户余额", user.getScore());
        map.put("等级角色", getMemberType(user.getMember_type()));
        map.put("邀请人ID", user.getRecommend_id());
        map.put("团队名称", user.getTeam_name());
        map.put("团队ID", user.getTeam_id());
        map.put("总收入", user.getAccumulative_total_score());
        map.put("创建时间", user.getCreate_time());
        return map;
    }

    /**
     * excel 内容组装
     *
     * @param user 普通客户信息
     */
    public Map<String, Object> createExcelContent_ordinarylist(AppUserDTO user) {
        Map map = new LinkedHashMap();
        map.put("用户编号", user.getUser_id());
        map.put("手机号码", user.getPhone());
        map.put("微信昵称", user.getNickname());
        map.put("用户姓名", user.getUser_name());
        map.put("身份证", user.getId_cade());
        map.put("邀请人ID", user.getRecommend_id());
        map.put("邀请人姓名", user.getRecommend_name());
        map.put("邀请人等级", getMemberType(user.getRecommend_member_type()));
        map.put("创建时间", user.getCreate_time());
        return map;
    }

    private String getMemberType(int memberType) {
        String member_type = "";
        // 会员类型  0:客户  1：分销员  2：团长  3：省长
        switch (memberType) {
            case 0:
                member_type = "客户";
                break;
            case 1:
                member_type = "分销员";
                break;
            case 2:
                member_type = "团长";
                break;
            case 3:
                member_type = "省长";
                break;
            default:
                break;
        }
        return member_type;
    }

    @Override
    public Boolean importWorkersInfo(int companyId, InputStream inputstream) {
        HSSFWorkbook wb;
        Boolean result = true;
        try {
            wb = new HSSFWorkbook(inputstream);
            HSSFSheet sheet = wb.getSheetAt(0);
            // 获得总行数
            int rows = sheet.getLastRowNum();
            if (rows >= 1) {
                // 遍历所有行,因为第一行为目录，所以去掉第一行，起始行数为1
                for (int i = 1; i <= rows; i++) {
                    HSSFRow row = sheet.getRow(i);
                    if (row == null) {
                        continue;
                    }
                    // 员工编号
                    String user_id = WeiXinUtils.getCellValue(row.getCell(0));
                    if (!StringUtils.isInteger(user_id)) {
                        continue;
                    }
                    // 将要更改的内容的查询条件
                    Bson filter = Filters.eq("user_id", Integer.parseInt(user_id));
                    // 更改的内容
                    Document doc = new Document();
                    String phone = WeiXinUtils.getCellValue(row.getCell(1));
                    if (!StringUtils.isBlank(phone) && phone.indexOf("**") == -1) {
                        doc.append("phone", phone);
                    }
                    String unionid = WeiXinUtils.getCellValue(row.getCell(2));
                    if (!StringUtils.isBlank(unionid)) {
                        doc.append("unionid", unionid);
                    }
                    String nickname = WeiXinUtils.getCellValue(row.getCell(3));
                    if (!StringUtils.isBlank(nickname)) {
                        doc.append("nickname", nickname);
                    }
                    String memberType = WeiXinUtils.getCellValue(row.getCell(4));
                    if (!StringUtils.isBlank(memberType)) {
                        // 会员类型
                        switch (memberType) {
                            case "非会员":
                                doc.append("member_type", 0);
                                break;
                            case "消费会员":
                                doc.append("member_type", 1);
                                break;
                            case "推广会员":
                                doc.append("member_type", 2);
                                break;
                            default:
                                break;
                        }
                    }
                    String serviceType = WeiXinUtils.getCellValue(row.getCell(5));
                    if (!StringUtils.isBlank(serviceType)) {
                        switch (serviceType) {
                            case "售前":
                                doc.append("service_type", 1);
                                break;
                            case "售后":
                                doc.append("service_type", 2);
                                break;
                            case "追访":
                                doc.append("service_type", 3);
                                break;
                            case "追访售后":
                                doc.append("service_type", 4);
                                break;
                            case "增值":
                                doc.append("service_type", 5);
                                break;
                            case "增值售后":
                                doc.append("service_type", 6);
                                break;
                            default:
                                break;
                        }
                    }
                    String customerName = WeiXinUtils.getCellValue(row.getCell(6));
                    if (!StringUtils.isBlank(customerName)) {
                        doc.append("custom_name", customerName);
                    }
                    String sysGroupName = WeiXinUtils.getCellValue(row.getCell(7));
                    if (!StringUtils.isBlank(sysGroupName)) {
                        doc.append("sys_group_name", sysGroupName);
                    }
                    String bankInfo = WeiXinUtils.getCellValue(row.getCell(8));
                    if (!StringUtils.isBlank(bankInfo)) {
                        String[] list = bankInfo.split(",");
                        if (list.length > 0) {
                            doc.append("bankCardInfo.card_id", list[0]);
                        }
                        // 加密的银行卡信息就不做更改
                        if (list.length > 1 && list[1].indexOf("***") == -1) {
                            doc.append("bankCardInfo.bank_name", list[1]);
                        }
                        if (list.length > 2) {
                            doc.append("bankCardInfo.bank_type", list[2]);
                        }
                        if (list.length > 3) {
                            doc.append("bankCardInfo.owner_name", list[3]);
                        }
                    }
                    String createTime = WeiXinUtils.getCellValue(row.getCell(9));
                    if (!StringUtils.isBlank(createTime)) {
                        doc.append("create_time", String.valueOf(DateUtil.getTime(createTime)));
                    }
                    String lastBuyTime = WeiXinUtils.getCellValue(row.getCell(10));
                    if (!StringUtils.isBlank(lastBuyTime)) {
                        doc.append("last_buy_time", String.valueOf(DateUtil.getTime(lastBuyTime)));
                    }
                    this.updateMany(doc, filter, companyId);
                }
            }
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputstream);
            return result;
        }
    }

    @Override
    public List<AppUserEntity> getAppUserListByFilter(Bson filter, int company_id) {
        List<String> list = appUserRepository.getAppUserListByUserId(filter, company_id);
        List<AppUserEntity> appUserList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) return appUserList;
        for (String str : list) {
            appUserList.add(new Gson().fromJson(str, AppUserEntity.class));
        }
        return appUserList;
    }

    @Override
    public AppUserEntity getAppUserByFilter(Bson filter, int company_id) {
        String str = appUserRepository.getAppUserByFilter(filter, company_id);
        AppUserEntity entity = new AppUserEntity();
        if (!StringUtil.isBlank(str)) {
            entity = new Gson().fromJson(str, AppUserEntity.class);
        }
        return entity;
    }

    @Override
    public List<Integer> getAppUserIdList(Bson filter, int company_id) {
        List<String> list = appUserRepository.getAppUserListByUserId(filter, company_id);
        List<Integer> userIdList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            Gson gson = new Gson();
            for (String str : list) {
                AppUserEntity entity = gson.fromJson(str, AppUserEntity.class);
                userIdList.add(entity.getUser_id());
            }
        }
        return userIdList;
    }

    @Override
    public boolean editRechargeBanlance(RechargeBalanceVO entity) {
        Integer companyID = entity.getCompany_id();
        Integer user_id = entity.getUser_id();
        Double balance = entity.getEdit_banlance();
        Integer recharge_type = entity.getRecharge_type();
        if (StringUtil.isBlank(companyID) || StringUtil.isBlank(user_id) || StringUtil.isBlank(balance)
                || StringUtil.isBlank(recharge_type)) {
            throw new BadRequestException("参数错误!");
        }
        String appUserStr = appUserRepository.getAppUserByFilter(Filters.eq("user_id", user_id), companyID);
        if (StringUtils.isBlank(appUserStr)) {
            throw new BadRequestException("不存在该用户!");
        }
        AppUserEntity appUserEntity = new Gson().fromJson(appUserStr, AppUserEntity.class);
        double recharge_balance = appUserEntity.getScore();
        String remark = "";
        if (recharge_type == 0) {
            recharge_balance += balance;
            remark = "增加";
        } else {
            recharge_balance = recharge_balance - balance;
            remark = "扣除";
            if (recharge_balance < 0) {
                recharge_balance = 0.0;
            }
        }
        Document document = new Document();
        BigDecimal bg = new BigDecimal(recharge_balance);
        document.append("recharge_balance", bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        // 修改用户的余额
        boolean balance_flag = appUserRepository.updateAppUser(document, Filters.eq("user_id", user_id), companyID);
        if (!balance_flag) {
            throw new BadRequestException("用户余额修改失败!");
        }
        // 生成流水
        AccountDetailEntity detail = new AccountDetailEntity();
        detail.setCompany_id(companyID); // 公司id
        detail.setUser_id(user_id); // 用户id
        detail.setAccount_money(balance); // 操作的金额
        detail.setAccount_state(recharge_type); // 收支状态 0收入 1支出
        detail.setAccount_type(recharge_type);// 收支类型 0收入 1支出
        detail.setHappen_proceed(6 + recharge_type);// 发生事项 0佣金收入 1佣金提现 3订单消费 4充值卡充值 5退款 6:客户管理操作
        String create_time = String.valueOf(System.currentTimeMillis());
        detail.setAccount_no(create_time); // 流水编号
        detail.setCreat_time(create_time); // 创建时间
        detail.setDeal_time(create_time); // 创建时间
        detail.setName(appUserEntity.getNickname());
        detail.setUnionid(appUserEntity.getUnionid());
        detail.setResult_type(1);
        detail.setPhone(appUserEntity.getPhone());
        detail.setMember_type(appUserEntity.getMember_type());
        detail.setRecharge_balance(balance);
        detail.setRemark("系统客服:" + SecurityUtils.getUsername() + "客户管理操作" + remark + "余额:" + balance);
        boolean detail_flag = accountDetaiRepository.insertOne(companyID, new Gson().toJson(detail));
        if (!detail_flag) {
            throw new BadRequestException("用户余额修改成功，流水生成失败!");
        }
        return true;
    }

    @Autowired
    private UserService userService;

    @Override
    public Object getClerkAndPage(UserQueryCriteria criteria, Pageable pageable) {
        // 返回结果定义，初始化
        List<InviterDTO> resultList = new ArrayList<>();
        // 获取分页后的用户集合
        Page<User> page = this.getUserList(criteria, pageable);
        if (CollectionUtils.isNotEmpty(page.getContent())) {
            // 所查的电话号集合定义，初始化
            List<String> phoneList = new ArrayList<>();
            // 遍历用户信息，取得用户手机号集合，去登录粉丝表查询相应的粉丝信息，用户绑定mongodb粉丝表的粉丝id
            page.getContent().forEach(info -> phoneList.add(info.getPhone()));
            Document filter = new Document("phone", new Document("$in", phoneList));
            Document project = new Document("user_id", 1).append("phone", 1);
            List<AppUserEntity> userList = appUserRepository.getListAndProject(criteria.getCompanyId(), filter,
                    project);
            // 数据重组，组成新的集合，业务员集合
            for (User info : page.getContent()) {
                InviterDTO entity = new InviterDTO();
                entity.setPhone(info.getPhone());
                entity.setUserName(info.getUsername());
                entity.setUserId(String.valueOf(info.getId()));
                // 用户在登录粉丝表的粉丝编号
                entity.setCustomerId(this.getAppUserIdByPhone(info.getPhone(), userList));
                resultList.add(entity);
            }
        }
        return PageUtil.toPage(resultList, page.getTotalElements());
    }

    /**
     * 获取分页后的用户集合
     *
     * @param criteria 查询条件
     * @param pageable 分页
     * @return
     */
    private Page<User> getUserList(UserQueryCriteria criteria, Pageable pageable) {
        // 因查询条件共用此字段，当为六位数编号时，需要去查mongodb的APP、小程序的登录粉丝表
        if (StringUtils.isInteger(criteria.getBlurry()) && criteria.getBlurry().length() == 6) {
            Document filter = new Document("user_id", Integer.parseInt(criteria.getBlurry()));
            AppUserEntity entity = this.getAppUserByFilter(filter, criteria.getCompanyId());
            // 根据粉丝编号去查找粉丝，若电话号为空，则代表没有找到，登录的用户表继续用此编号去查找用户，当然一般是找不到的
            // 最终的目的就是，用粉丝编号找到粉丝得到电话号，用电话号去查找用户
            criteria.setBlurry(StringUtils.isBlank(entity.getPhone()) ? criteria.getBlurry() : entity.getPhone());
        }
        Page<User> page = userService.queryListAndPage(criteria, pageable);
        return page;
    }

    /**
     * 通过电话号获取登录粉丝的编号
     *
     * @param phone
     * @param userList
     * @return
     */
    private String getAppUserIdByPhone(String phone, List<AppUserEntity> userList) {
        if (CollectionUtils.isNotEmpty(userList)) {
            for (AppUserEntity info : userList) {
                if (StringUtils.isBlank(phone))
                    return "";
                if (phone.equals(info.getPhone())) {
                    return String.valueOf(info.getUser_id());
                }
            }
        }
        return "";
    }

    /**
     * 解题思路：
     * 1.获取邀请人信息，一直找到他的根节点
     * 2.比对需要绑定邀请人信息包含根节点内容，若包含，则返回，因为违背了节点之间的关系，解决方法是，要么不绑定与节点冲突的内容，
     * 要么把冲突的节点解绑
     * 3.若能够更新内容，更新绑定的用户id，并且在客服id不为空的情况下，绑定客服(也就是后台登录的用户)
     * 4.绑定了邀请人之后，需要判断邀请人是否满足升级为推广会员
     *
     * @param entity
     * @return
     */
    @Override
    public Map updateUserInviter(InviterVO entity) {
        // id集合转换为Integer类型
        List<Integer> idToInteger = this.getIdListToInteger(entity.getCustomerIdList());
        Integer customer_id = Integer.parseInt(entity.getCustomerId());
        if (idToInteger.contains(customer_id)) {
            // 自己不能绑定自己
            return ReturnMapUtil.returnMap(false, InviterEnum.getName(5));
        }
        // 邀请人信息
        AppUserEntity inviter = this.getAppUserByFilter(new Document("user_id", customer_id),
                entity.getCompany_id());
        if (inviter.getUser_id() == 0) {
            // 邀请人不存在
            return ReturnMapUtil.returnMap(false, InviterEnum.getName(0));
        }
        // 去重，需要绑定邀请人id的用户
        List<Integer> idList = this.idListFilter(entity, idToInteger);
        if (idList.isEmpty()) {
            // 去重绑定，已经绑定过此邀请人的就不要在进行更新操作了，全部都是已绑定
            return ReturnMapUtil.returnMap(false, InviterEnum.getName(4));
        }
        // 邀请人的节点信息，一直查到原生根节点，若需要绑定邀请人是邀请人的上级，则不让绑定
        List<Integer> parentIdList = new ArrayList<>();
        this.recursionQuery(parentIdList, inviter.getRecommend_id(), entity.getCompany_id());
        // 查看交集内容,若交集内容大于0，则需要绑定邀请人是邀请人的上级
        parentIdList.retainAll(idList);
        if (parentIdList.size() > 0) {
            // 需要绑定邀请人id的是邀请人的上级
            String id = StringUtils.join(parentIdList, ",");
            return ReturnMapUtil.returnMap(false, InviterEnum.getName(3) + id);
        }
        // 给指定的用户绑定的邀请人、业务员信息，其实都是一个意思，意思是说这个人由谁来负责、由谁推荐的
        Document doc = new Document();
        doc.append("recommend_id", customer_id);
        doc.append("recommend_date", String.valueOf(System.currentTimeMillis()));
        doc.append("pnickname", inviter.getNickname());
        if (StringUtils.isNotBlank(entity.getUserName())) {
            // 邀请人在后台的账号信息
            doc.append("custom_id", entity.getUserId());
            doc.append("custom_name", entity.getUserName());
        }
        // 更新绑定信息
        Bson filter_update = Filters.in("user_id", idList);
        this.updateMany(doc, filter_update, entity.getCompany_id());
        return ReturnMapUtil.returnMap(true, InviterEnum.getName(1));
    }

    /**
     * 当前可以操作的用户一定是团长角色的
     * 当团长的团队id发生变化
     * 下级用户的团队id也需要跟着团长发生相对应的变化
     *
     * @param vo
     * @return
     */
    @Override
    public Map updateUserTeam(InviterVO vo) {
        Integer company_id = vo.getCompany_id();
        String[] customerIdList = vo.getCustomerIdList().split(",");
        List<Integer> userIds = new ArrayList<>();
        // 类型转换
        Arrays.asList(customerIdList).forEach(id -> userIds.add(Integer.parseInt(id)));
        // 根据传入的id查询用户信息，ps：角色是团长/分销员
        Document doc = new Document("user_id", new Document("$in", userIds))
                .append("member_type", new Document("$in", Arrays.asList(1, 2)));
        List<String> users = appUserRepository.getAppUserListByUserId(doc, company_id);
        if (CollectionUtils.isEmpty(users)) {
            return ReturnMapUtil.returnMap(true, InviterEnum.getName(6));
        }

        List<Integer> upUserIds = new ArrayList<>();
        // 获得用户信息(团长/分销员)
        for (String user : users) {
            AppUserEntity entity = new Gson().fromJson(user, AppUserEntity.class);
            upUserIds.add(entity.getUser_id());
            if (StringUtil.isBlank(entity.getTeam_id())) continue;
            List<Document> doc_team = Arrays.asList(
                    new Document("team_id", entity.getTeam_id()),
                    new Document("team_id", ""),
                    new Document("team_id", null),
                    new Document("team_id", new Document("$exists", false))
            );

            // 判断当前该用户角色等级，如果是团长向下找两级，如果是客户 向下找一级
            switch (entity.getMember_type()) {
                case 2:
                    // 获得当前用户的下级用户集合(分销员)
                    Document doc_f = new Document("recommend_id", entity.getUser_id())
                            .append("member_type", 1)
                            .append("$or", doc_team);
                    List<String> users_f = appUserRepository.getAppUserListByUserId(doc_f, company_id);
                    // 检查是否有下级分销员，没有则进行下一个用户
                    if (CollectionUtils.isEmpty(users_f)) continue;
                    // 查找分销员下级的客户信息（客户）
                    for (String user_f : users_f) {
                        AppUserEntity entity_f = new Gson().fromJson(user_f, AppUserEntity.class);
                        // 分销员id添加
                        upUserIds.add(entity_f.getUser_id());
                        // 获得客户信息
                        Document doc_k = new Document("recommend_id", entity_f.getUser_id()).append("member_type", 0)
                                .append("$or", doc_team);
                        List<String> users_k = appUserRepository.getAppUserListByUserId(doc_k, company_id);
                        // 检查是否有客户信息
                        if (CollectionUtils.isEmpty(users_k)) continue;
                        users_k.forEach(user_k -> upUserIds.add(new Gson().fromJson(user_k, AppUserEntity.class).getUser_id()));
                    }
                    break;
                case 1:
                    // 获得客户信息
                    Document doc_k = new Document("recommend_id", entity.getUser_id()).append("member_type", 0)
                            .append("$or", doc_team);
                    List<String> users_k = appUserRepository.getAppUserListByUserId(doc_k, company_id);
                    // 检查是否有客户信息
                    if (CollectionUtils.isEmpty(users_k)) continue;
                    users_k.forEach(user_k -> upUserIds.add(new Gson().fromJson(user_k, AppUserEntity.class).getUser_id()));
                    break;
                default:
                    break;

            }
        }
        String team_s = teamRepository.findOne(company_id, new Document("team_id", vo.getCustomerId()));
        TeamEntity team = StringUtil.isBlank(team_s) ? new TeamEntity() : new Gson().fromJson(team_s, TeamEntity.class);
        // 批量修改用户的团队id
        boolean bool = appUserRepository.updateManyByIds(
                new Document("team_id", vo.getCustomerId())
                        .append("team_name", team.getTeam_name()),
                new Document("user_id", new Document("$in", upUserIds)),
                company_id
        );

        return ReturnMapUtil.returnMap(bool, InviterEnum.getName(7));
    }

    @Override
    public int getMaxUserId(int companyId) {
        Bson filter = new Document();
        Bson sort = new Document("user_id", -1);
        List<String> list = appUserRepository.getAppUserByFilterSortSkipLimit(filter, sort, 0, 1, companyId);
        if (CollectionUtils.isEmpty(list)) return 100001;
        AppUserEntity entity = new Gson().fromJson(list.get(0), AppUserEntity.class);
        return entity.getUser_id();
    }

    @Override
    public boolean updateUserMemberType(AppUserEntity entity) {
        Document update = new Document("member_type", entity.getMember_type()).append("user_name", entity.getUser_name());
        // 更新后台用户至移动端用户表，有则作编辑，没有则做新增
        if (entity.getUser_id() == 0) {
            entity.setUser_id(getMaxUserId(entity.getCompany_id()) + 1);
            // 不是团队负责人
            update.append("active_team", 0);
        }
        Bson filter = new Document("user_id", entity.getUser_id()).append("phone", entity.getPhone());
        appUserRepository.updateEntity(entity.getCompany_id(), filter, update, true);
        return false;
    }

    /**
     * 递归查询绑定的邀请人id组成的集合，一直查到原生的根节点
     *
     * @param idList    递归查询到的id组成的集合
     * @param userId    递归查询的条件。recommend_id也就是parentid，父节点id
     * @param companyId 公司id
     */
    private void recursionQuery(List<Integer> idList, Integer userId, Integer companyId) {
        if (userId > 0) {
            AppUserEntity inviter = this.getAppUserByFilter(new Document("user_id", userId), companyId);
            if (inviter.getUser_id() > 0) {
                idList.add(inviter.getUser_id());
                this.recursionQuery(idList, inviter.getRecommend_id(), companyId);
            }
        }
    }

    /**
     * 需要绑定邀请人id的条件过滤 1.邀请人id已经存在于当前所取用户身上
     *
     * @param entity       页面传来的实体类
     * @param userIdFilter 需要过滤的id集合
     * @return
     */
    private List<Integer> idListFilter(InviterVO entity, List<Integer> userIdFilter) {
        // 需要进行绑定邀请人的用户id集合
        List<Integer> userIdList = new ArrayList<>();
        // 查询将要绑定邀请人的用户信息
        Bson filter = Filters.in("user_id", userIdFilter);
        List<AppUserEntity> list = this.getAppUserListByFilter(filter, entity.getCompany_id());
        if (CollectionUtils.isNotEmpty(list)) {
            for (AppUserEntity info : list) {
                // 邀请人id已经存在于当前所取用户身上，不做变动
                if (Integer.parseInt(entity.getCustomerId()) == info.getRecommend_id()) {
                    continue;
                }
                userIdList.add(info.getUser_id());
            }
        }
        return userIdList;
    }

    /**
     * 用户类型修改为推广会员
     *
     * @param companyId
     * @param recommendId
     */
    private void memberTypeUpdate(Integer companyId, Integer recommendId) {
        // 发生了用户绑定邀请人，此时需要判断邀请人满不满足升级为推广会员
        int recommendNum = this.countNum(companyId, new Document("recommend_id", recommendId));
        if (recommendNum > 30) {
            Bson userFilter = new Document("user_id", recommendId);
            Document update = new Document("member_type", 2);
            this.updateMany(update, userFilter, companyId);
        }
    }

    /**
     * id集合转List<Integer>
     *
     * @param ids
     * @return
     */
    private List<Integer> getIdListToInteger(String ids) {
        List<Integer> userId = new ArrayList<>();
        if (StringUtils.isBlank(ids)) {
            return userId;
        }
        // 需要进行操作修改的用户的id
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            if (StringUtil.isInteger(id)) {
                userId.add(Integer.parseInt(id));
            }
        }
        return userId;
    }

}
